package com.jiantong.admin.controller.management;


import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.user.model.*;

import com.jiantong.user.model.SysModules;
import com.jiantong.user.service.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by ThinkPad on 2017/8/8.
 */
@Controller
@RequestMapping("/management/role")
public class RoleManagementController {

    @RpcConsumer
    private SysModuleReadService sysModuleReadService;
    @RpcConsumer
    private RoleModlueReadService roleModlueReadService;
    @RpcConsumer
    private RoleModlueWriteService roleModlueWriteService;
    @RpcConsumer
    private RolesWebWriteService rolesWebWriteService;
    @RpcConsumer
    private RolesWebReadService rolesWebReadService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private GovernmentReadService governmentReadService;
    @RpcConsumer
    private  GovernmentUserDutyReadService governmentUserDutyReadService;
    @RpcConsumer
    private UserReadService userReadService;

    @GetMapping("/addrole")
    public String test(Model model, HttpServletResponse response, HttpServletRequest request) {
        List<SysModules> sysModulesType1 = new ArrayList<>();
        List<SysModules> sysModulesType2 = new ArrayList<>();
        List<SysModules> sysModulesType3 = new ArrayList<>();
        List<SysModules> sysModulesList = sysModuleReadService.SelectAll(new HashMap()).getResult();
        for (SysModules sysModules : sysModulesList) {
            switch (sysModules.getType()) {
                case 1:
                    sysModulesType1.add(sysModules);
                    break;
                case 2:
                    sysModulesType2.add(sysModules);
                    break;
                case 3:
                    sysModulesType3.add(sysModules);
                    break;

            }
        }

        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        model.addAttribute("sysModulesType1", sysModulesType1);

        return "management/role/addRole";


    }

    @GetMapping("/findChild")
    @ResponseBody
    public List<SysModules> findChild(@RequestParam Long parentId) {
        Map criteria = new HashMap();
        criteria.put("parentId", parentId);
        List<SysModules> smList = sysModuleReadService.selectChild(criteria).getResult();
        return smList;
    }

    @GetMapping("/findFirst")
    @ResponseBody
    public List<SysModules> findFirst(@RequestParam Integer type) {
        Map criteria = new HashMap();
        criteria.put("type", type);
        List<SysModules> smList = sysModuleReadService.selectFirst(criteria).getResult();
        return smList;
    }


    @GetMapping("/updateRole")
    public String updateRole() {
        return "management/role/updateRole";
    }

    @GetMapping("/oldRole")
    @ResponseBody
    public List<Long> oldRole(@RequestParam Long id) {
        List<Long> idList = roleModlueReadService.selectModuleByRoleId(id);
        return idList;
    }

    @GetMapping("/doUpdateRole")
    @ResponseBody
    public Boolean doUpdateRole(@RequestParam Long id,
                                @RequestParam String ids) {
        List<Long> moduleList = roleModlueReadService.selectModuleByRoleId(id);
        List arrList = new ArrayList();
        List<Long> ids2 = new ArrayList<>();
        List<Long> list1 = new ArrayList<>();
        String[] list = ids.split(",");

        for (int i = 0; i < list.length; i++) {
            int id2 = Integer.parseInt(list[i]);
            Long id1 = Integer.toUnsignedLong(id2);
            list1.add(id1);
        }

        arrList.addAll(list1);
        arrList.retainAll(moduleList);
        moduleList.removeAll(arrList);

        return changeRoleAndModule(id, list1, moduleList);
    }

    @RequestMapping("insertRole")
    @ResponseBody
    public int aaaaa(@RequestParam String roleName,
                     @RequestParam String infomation,
                     @RequestParam String modules) {
        //查看数据库是否有该角色
        Map map = new HashMap();
        map.put("name", roleName);
        List<RolesWeb> rolesWebList = (List<RolesWeb>) rolesWebReadService.findbykeyword(map).getResult();

        if (rolesWebList.size() > 0) {
            return 1000;
        }
        //创建角色
        RolesWeb rolesWeb = new RolesWeb();
        rolesWeb.setName(roleName);
        rolesWeb.setInfomation(infomation);
        rolesWeb.setOrder("0");
        rolesWeb.setStatus(1);
        rolesWeb.setType(0);

        Response<Long> longResponse = rolesWebWriteService.create(rolesWeb);
        if (longResponse == null || longResponse.getResult() < 0) {
            return -1;
        }

        Long roleId = longResponse.getResult();

        //将moudes字符串转换成
        List<RoleModlue> list1 = new ArrayList<>();
        String[] list = modules.split(",");

        for (int i = 0; i < list.length; i++) {
            int id = Integer.parseInt(list[i]);
            Long id1 = Integer.toUnsignedLong(id);
            RoleModlue roleModlue = new RoleModlue();
            roleModlue.setModuleId(id1);
            roleModlue.setIsRight(1);
            roleModlue.setRoleId(roleId);
            list1.add(roleModlue);
        }
        //创建一组角色对应的模块权限

        Integer longResponse1 = roleModlueWriteService.creates(list1);

        if (longResponse1 == null || longResponse1 < 0) {
            return -1;
        }
        return 1;
    }

    public void bbbbbb(@RequestParam Long roleId,
                       @RequestParam String modules) {

        //查询该角色对应模块权限关联表id集合
        Map map = new HashMap();
        map.put("roleId", roleId);
        List<RoleModlue> roleModlueList = roleModlueReadService.finkeyword(map);
        List<Long> longList = new ArrayList<>();
        for (RoleModlue roleModlue : roleModlueList) {
            longList.add(roleModlue.getId());
        }
        //先通过ID集合删除该角色对应所有模块
        int a = roleModlueWriteService.deletes(longList);
        //增加该角色更改后的所有模块
        List<RoleModlue> list1 = new ArrayList<>();
        String[] list = modules.split(",");
        //将moudes字符串转换成
        for (int i = 0; i < list.length; i++) {
            int id = Integer.parseInt(list[i]);
            Long id1 = Integer.toUnsignedLong(id);
            RoleModlue roleModlue = new RoleModlue();
            roleModlue.setModuleId(id1);
            roleModlue.setIsRight(1);
            roleModlue.setRoleId(roleId);
            list1.add(roleModlue);
        }

        roleModlueWriteService.creates(list1);
    }

    @Transactional
    private Boolean changeRoleAndModule(Long id, List<Long> ids, List moduleList) {
        Boolean b = false;
        if (moduleList != null && moduleList.size() > 0) {
            Map criteria = new HashMap();
            criteria.put("roleId", id);
            criteria.put("list", moduleList);
            b = roleModlueWriteService.delByModuleIdAndRoleId(criteria);
        } else {
            b = true;
        }

        List<RoleModlue> roleList = new ArrayList<>();
        for (Long moduleId : ids) {

            RoleModlue roleModlue = new RoleModlue();
            roleModlue.setRoleId(id);
            roleModlue.setModuleId(moduleId);
            roleList.add(roleModlue);
        }
        Boolean a = roleModlueWriteService.creates(roleList) > 0;
        return a && b;
    }


    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6 = new HashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }

                        map.put("cityAreaDtoList", cityAreaDtoList);
                        map.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        UserProfile userProfile2 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String city1 = userProfile2.getCity();
                        Map map7 = new HashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map map21 = new HashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }

                        map.put("cityAreaDtoList", cityAreaDtoList1);
                        map.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        UserProfile userProfile3 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String region = userProfile3.getRegion();
                        Map map36 = new HashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map map31 = new HashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList3);
                        map.put("breedFactorys", breedFactoryList3);

                        //switch break;
                        break;
                    case 4://镇
                        UserProfile userProfile4 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String street = userProfile4.getStreet();
                        Map map46 = new HashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map map41 = new HashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);

                        map.put("cityAreaDtoList", cityAreaDtoList4);
                        map.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        UserProfile userProfile5 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();

                        List<GovernmentUserDuty> governmentUserDutyList = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null).getResult();
                        List<Long> longlist = new ArrayList<>();
                        if (governmentUserDutyList.size()!=0){
                            for (GovernmentUserDuty governmentUserDuty : governmentUserDutyList) {
                                longlist.add(governmentUserDuty.getFactoryOrPointId());
                            }
                        }
                        List<String> villages = new ArrayList<>();
                        List<BreedFactory> breedFactoryList2 = breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory : breedFactoryList2) {
                            villages.add(breedFactory.getVillage());
                            ;
                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5 = new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);
                        map.put("userProfile", userProfile5);


                        map.put("cityAreaDtoList", cityAreaDtoList5);
                        map.put("breedFactorys", breedFactoryList2);
                        //switch break;
                        //switch break;
                        break;
                }


                break;
            }

        }

        return map;
    }


    public List findFactoryIdByArea(String region, int breedType) {

        Map map = new HashMap();
        if (breedType == -1) {
            map.put("breedType", null);
        } else {
            map.put("breedType", breedType);
        }
        List<String> list1 = new ArrayList<>();
        String[] list = region.split(",");

        for (int i = 0; i < list.length; i++) {
            list1.add(list[i]);
        }
        map.put("areas", list1);

        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();

        return breedFactoryList;
    }

}
